package com.cabal.module.web;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义过滤器
 *
 * @author shenkang
 * @since JDK8
 * Creation time：2020/10/12
 */
public class StreamFilter implements Filter {

    public static final String REQUEST_GET = "GET";

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 防止流读取一次后就没有了, 所以需要将流继续写出去
        if(request.getMethod().equalsIgnoreCase(REQUEST_GET)){
            filterChain.doFilter(request, response);
        }else{
            String contentType = request.getContentType();
            if(contentType != null && contentType.contains("multipart")){
                filterChain.doFilter(request, response);
            }else{
                ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
                filterChain.doFilter(requestWrapper, response);
            }
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        this.doFilterInternal((HttpServletRequest)request,(HttpServletResponse)response,chain);
    }

    @Override
    public void destroy() {

    }
}
